<template>
    <div style="padding: 0px;height: 100vh; width: 1200px;max-width: 1200px;margin: 0 auto;">
        <div style="display: flex;justify-content: space-between;">
            <router-link to="/main/renshi/kaoqing/kqguanli" style=""><button>返回</button></router-link>
            <span>
                <button @click="addRecord" v-if="!isView">新增</button>
                <button @click="saveRecords" v-if="!isView">保存</button>
                <button @click="deleteSelected" v-if="!isView">删除</button>
                <button @click="goToList">列表</button>
            </span>
        </div>
        <h2>刷卡异常登记表</h2>
        <div style="max-width: 1200px;margin: 0 auto;overflow: auto;height: 380px">
            <table border="1">
                <thead>
                    <tr>
                        <th rowspan="3" v-if="!isView"><input type="checkbox" :checked="isAllSelected"
                                :indeterminate="isPartiallySelected" @click="toggleAllSelection"></th>
                        <th rowspan="3">序号</th>
                        <th rowspan="3">工号</th>
                        <th rowspan="3">姓名</th>
                        <th rowspan="3">部门</th>
                        <th rowspan="3">日期</th>
                        <th colspan="8">异常时间（实际刷卡时间）</th>
                        <th rowspan="3">员工签名</th>
                        <th rowspan="3">当班保安签名确认</th>
                        <th rowspan="3">备注（异常原因）</th>
                    </tr>
                    <tr>
                        <td colspan="6">正班</td>
                        <td colspan="2">加班</td>
                    </tr>
                    <tr>
                        <td>上班1</td>
                        <td>下班1</td>
                        <td>上班2</td>
                        <td>下班2</td>
                        <td>上班3</td>
                        <td>下班3</td>
                        <td>上班3</td>
                        <td>下班3</td>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in records" :key="index">
                        <td v-if="!isView"><input type="checkbox" @click="toggleSelection(index)"
                                v-model="selectedIndices" :value="index">
                        </td>
                        <td>{{ index + 1 }}</td>
                        <td><input type="text" v-model="item.employeeId" :disabled="isView"></td>
                        <td><input type="text" v-model="item.name" :disabled="isView"></td>
                        <td><input type="text" v-model="item.department" :disabled="isView"></td>
                        <td><input type="date" v-model="item.recordDate" :disabled="isView"></td>
                        <td><input type="time" v-model="item.normalWorkStartTime1" :disabled="isView"></td>
                        <td><input type="time" v-model="item.normalWorkEndTime1" :disabled="isView"></td>
                        <td><input type="time" v-model="item.normalWorkStartTime2" :disabled="isView"></td>
                        <td><input type="time" v-model="item.normalWorkEndTime2" :disabled="isView"></td>
                        <td><input type="time" v-model="item.normalWorkStartTime3" :disabled="isView"></td>
                        <td><input type="time" v-model="item.normalWorkEndTime3" :disabled="isView"></td>
                        <td><input type="time" v-model="item.overtimeStartTime1" :disabled="isView"></td>
                        <td><input type="time" v-model="item.overtimeEndTime1" :disabled="isView"></td>
                        <td><input type="text" v-model="item.employeeSignature" :disabled="isView"></td>
                        <td><input type="text" v-model="item.securitySignature" :disabled="isView"></td>
                        <td><input type="text" v-model="item.remark" :disabled="isView"></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <p>注：1、此表仅限于考勤机异常、考勤卡异常造成不能正常刷卡时，在各分公司保安岗/办公楼前台处登记使用；<br>
            2、此表由当事人在发生刷卡异常时按实际情况/实际时间（正楷字）填写，同时需当班保安签名确认后方可生效；<br>
            3、此表由保安员次日上午08:30交于分公司人资处，作为修改当次/日考勤依据。<br>
            4、行政组对此表记录的有效性、正确性负责。</p>
        <p style="display:flex;justify-content: space-between;"><span>表单编号及版本：AM-JY-077 A/0</span> <span>保存期限：长期</span>
        </p>
    </div>
</template>

<script>
import { getCardExceptionRecordDetail, saveCardExceptionRecord, batchSaveCardExceptionRecord } from '@/api/cardExceptionRecord'
import { Message } from 'element-ui'
import { formatDate, formatTime } from '@/utils/date.js'

export default {
    data() {
        return {
            isView: false,
            isEdit: false,
            records: [
                this.getEmptyRecord()
            ],
            selectedIndices: []
        };
    },
    computed: {
        // 判断是否全选
        isAllSelected() {
            return this.selectedIndices.length === this.records.length;
        },
        // 判断是否部分选中
        isPartiallySelected() {
            return this.selectedIndices.length > 0 && this.selectedIndices.length < this.records.length;
        }
    },
    created() {
        // 获取路由参数
        const { id, type } = this.$route.query;
        if (id) {
            if (type === 'view') {
                this.isView = true;
            } else if (type === 'edit') {
                this.isEdit = true;
            }
            this.getDetail(id);
        }
    },
    methods: {
        goToList() {
            this.$router.push('/main/renshi/renshizhidu/skyichangdj/skyichangdjList')
        },
        getEmptyRecord() {
            return {
                id: null,
                employeeId: '',
                name: '',
                department: '',
                recordDate: '',
                normalWorkStartTime1: '',
                normalWorkEndTime1: '',
                normalWorkStartTime2: '',
                normalWorkEndTime2: '',
                normalWorkStartTime3: '',
                normalWorkEndTime3: '',
                overtimeStartTime1: '',
                overtimeEndTime1: '',
                employeeSignature: '',
                securitySignature: '',
                remark: ''
            };
        },
        async getDetail(id) {
            try {
                const response = await getCardExceptionRecordDetail(id);
                if (response.data && response.data.code === 200) {
                    const data = response.data.data;
                    if (data) {
                        // 格式化日期
                        data.recordDate = formatDate(data.recordDate);
                        data.normalWorkStartTime1 = formatTime(data.normalWorkStartTime1);
                        data.normalWorkEndTime1 = formatTime(data.normalWorkEndTime1);
                        data.normalWorkStartTime2 = formatTime(data.normalWorkStartTime2);
                        data.normalWorkEndTime2 = formatTime(data.normalWorkEndTime2);
                        data.normalWorkStartTime3 = formatTime(data.normalWorkStartTime3);
                        data.normalWorkEndTime3 = formatTime(data.normalWorkEndTime3);
                        data.overtimeStartTime1 = formatTime(data.overtimeStartTime1);
                        data.overtimeEndTime1 = formatTime(data.overtimeEndTime1);
                        this.records = [data];
                    }
                } else {
                    Message.error(response.data?.message || '获取详情失败');
                }
            } catch (error) {
                console.error('获取详情失败：', error);
                Message.error('获取详情失败：' + error.message);
            }
        },
        addRecord() {
            this.records.push(this.getEmptyRecord());
        },
        toggleAllSelection() {
            if (this.isAllSelected) {
                this.selectedIndices = [];
            } else {
                this.selectedIndices = this.records.map((_, index) => index);
            }
        },
        toggleSelection(index) {
            const selectedIndex = this.selectedIndices.indexOf(index);
            if (selectedIndex === -1) {
                this.selectedIndices.push(index);
            } else {
                this.selectedIndices.splice(selectedIndex, 1);
            }
        },
        validateRecords() {
            for (let i = 0; i < this.records.length; i++) {
                const record = this.records[i];
                if (!record.employeeId) {
                    Message.error(`第${i + 1}行工号不能为空`);
                    return false;
                }
                if (!record.name) {
                    Message.error(`第${i + 1}行姓名不能为空`);
                    return false;
                }
                if (!record.department) {
                    Message.error(`第${i + 1}行部门不能为空`);
                    return false;
                }
                if (!record.recordDate) {
                    Message.error(`第${i + 1}行日期不能为空`);
                    return false;
                }
            }
            return true;
        },
        async saveRecords() {
            if (!this.validateRecords()) {
                return;
            }

            try {
                let recordsToSave = this.records.map(record => {
                    return {
                        ...record,
                        recordDate: formatDate(record.recordDate),
                        normalWorkStartTime1: formatTime(record.normalWorkStartTime1),
                        normalWorkEndTime1: formatTime(record.normalWorkEndTime1),
                        normalWorkStartTime2: formatTime(record.normalWorkStartTime2),
                        normalWorkEndTime2: formatTime(record.normalWorkEndTime2),
                        normalWorkStartTime3: formatTime(record.normalWorkStartTime3),
                        normalWorkEndTime3: formatTime(record.normalWorkEndTime3),
                        overtimeStartTime1: formatTime(record.overtimeStartTime1),
                        overtimeEndTime1: formatTime(record.overtimeEndTime1)
                    };
                });

                let response;
                if (recordsToSave.length === 1) {
                    response = await saveCardExceptionRecord(recordsToSave[0]);
                } else {
                    response = await batchSaveCardExceptionRecord(recordsToSave);
                }

                if (response.data && response.data.code === 200) {
                    Message.success('保存成功');
                    this.$router.push('/main/renshi/renshizhidu/skyichangdj/skyichangdjList');
                } else {
                    Message.error(response.data?.message || '保存失败');
                }
            } catch (error) {
                console.error('保存失败：', error);
                Message.error('保存失败：' + error.message);
            }
        },
        deleteSelected() {
            if (this.selectedIndices.length === 0) {
                Message.warning('请选择要删除的记录');
                return;
            }

            this.selectedIndices.sort((a, b) => b - a).forEach(index => {
                this.records.splice(index, 1);
            });
            this.selectedIndices = [];

            if (this.records.length === 0) {
                this.addRecord();
            }
        }
    }
};
</script>

<style scoped>
table {
    border-collapse: collapse;
    width: 150%;
}

th,
td {
    border: 1px solid black;
    padding: 3px;
    white-space: nowrap;
}

p {
    text-align: left;
    line-height: 30px;
}

button {
    margin-top: 10px;
    margin-right: 10px;
    padding: 5px 10px;
    cursor: pointer;
    background-color: #409EFF;
    color: white;
    border: none;
    border-radius: 4px;
}

button:hover {
    background-color: #66b1ff;
}

button:disabled {
    background-color: #a0cfff;
    cursor: not-allowed;
}

input {
    background-color: transparent;
    font-size: 18px;
    font-family: '宋体';
    border: 0px;
    width: 100%;
}

input[type="checkbox"] {
    width: auto;
}

input:disabled {
    color: #606266;
    cursor: not-allowed;
}
</style>